package jnBase  
{
	import jnBase.components.GetRequest;
	import jnBase.eventdispatcher.JNEventDispatcher;
	import jnBase.script.ScriptSceneTools;
	import jnBase.view.SimpleLoading;
	
	import laya.ani.bone.Skeleton;
	import laya.components.Script;
	import laya.display.Sprite;
	import laya.events.Event;
	import laya.maths.Point;
	import laya.media.SoundManager;
	import laya.net.HttpRequest;
	import laya.ui.Dialog;
	import laya.utils.Browser;
	import laya.utils.Handler;
	import laya.utils.Tween;
	
	import ui.tools.EndUI;
	
	public class PSteps extends Script
	{
		private var _owner:*;
		public function PSteps()
		{
			super();
		}
		
		override public function onAwake():void
		{
			// TODO Auto Generated method stub
			super.onAwake();
			_owner=owner as InsPages;
			_owner.alpha=1;
			_owner.x=0;
			_owner.autoDestroyAtClosed=true;
			Tween.from(_owner,{x:1920,alpha:0},300);
			submitStepData();
		}
		/**
		 *告诉服务器当前位置 方便记录操作位置 
		 * 
		 */		
		private function submitStepData():void{
			var sonS:int=0;
			if(ShiyanControl.hasSonStep(Data.currStep)){
				sonS=Data.currSonStep+1;
			}
			else sonS=0;
			trace(_owner.name+":submitStepData:提交当前位置信息："+"stepId="+(Data.currStep+1)+"*"+sonS);
			Data.perStepTime=0;
			if(!Data.token){
				return ;
			}
			Api.AddStep(Data.operationType,Data.PracticeId,(Data.currStep+1)+"*"+sonS,Data.UsedTime,1,Data.perStepTime);
//			new HttpRequest().send(Data.HttpRequest+"Experiment/AddStep","PracticeId="+Data.PracticeId+"&stepId="+(Data.currStep+1)+"*"+sonS+"&Code="+Data.token+"&IsStart=0&ExamDuration=0","post");
		}
		override public function onEnable():void{
			JNEventDispatcher.getInstance().on(JNEventDispatcher.CLICK_SON_STEPS,this,changeSonSteps);
			JNEventDispatcher.getInstance().on(JNEventDispatcher.NATURAL_SON_STEPS,this,submitTime);
			JNEventDispatcher.getInstance().on("TimeOut",this,timeOut);
			(_owner as InsPages).changeSonStep();
			//			trace(_owner.name+"onEnable：进入主页面");
		}
		
		override protected function _onDisable():void{
			//			trace(_owner.name+"_onDisable：移除切换页面事件侦听");
			JNEventDispatcher.getInstance().off(JNEventDispatcher.CLICK_SON_STEPS,this,changeSonSteps);
			JNEventDispatcher.getInstance().off(JNEventDispatcher.NATURAL_SON_STEPS,this,submitTime);
			JNEventDispatcher.getInstance().off("TimeOut",this,timeOut);
			removeAllListener();
		}
		/**
		 *考核模式：实验超时 
		 * 
		 */		
		private function timeOut():void
		{
			// TODO Auto Generated method stub
			this.enabled=false;
//			(_owner as InsPages).reset();
//			(_owner as Scene).destroy();
		}
		/**
		 *更改二级目录时调用
		 * 
		 */		
		protected function changeSonSteps():void
		{
			//			trace(_owner.name+"当前选择子步骤:"+ShiYanData.currSonStep);
			removeAllListener();
			Data.perStepTime=0;
			Laya.timer.callLater(this,submitStepData);
			(_owner as InsPages).reset();
			(_owner as InsPages).changeSonStep();
		}	
		/**
		 *提交子步骤用时数据，只有一个步骤完成时才提交数据，点击按钮切换步骤的时候不提交数据
		 *增加第二步时，提交第一步的数据。 
		 * @param $step 从0开始
		 * @param $changeStep 是否切换步骤，如果切换步骤就在提交完数据后再继续切换步骤
		 * 如果不切换步骤就只提交数据
		 * 
		 */		
		private function sendAddStepRequest($sonstep:int,$changeStep:Boolean):void{
			if(!ShiyanControl.hasSonStep(Data.currStep)){
				$sonstep=0;
			}
			trace("当前步骤完成："+(Data.currStep+1)+"*"+$sonstep+"用时："+Data.perStepTime);
			if(Data.token) {
				Api.AddStep(Data.operationType,Data.PracticeId,(Data.currStep+1)+"*"+$sonstep,Data.UsedTime,0,Data.perStepTime,this,function(res){
					if(res.success){
						loading.close();
						if($changeStep) changeSonSteps();
					}
				});
//				http.send(Data.HttpRequest+"Experiment/AddStep","PracticeId="+Data.PracticeId+"&stepId="+(Data.currStep+1)+"*"+$sonstep+"&ExamDuration="+Data.perStepTime+"&Code="+Data.token+'&UsedTime='+Data.UsedTime,"post");
				var loading:SimpleLoading=new SimpleLoading();
				loading.show();
			}
			
		}
		/**
		 *取出正确的工具并执行指定的方法 
		 * @param $tip
		 * @param $value
		 * @param $fun
		 * @param $args
		 * 
		 */		
		public function tishiTools($tip:String,$value:String,$fun:Function,$args:Array=null):void{
			JNEventDispatcher.getInstance().once(JNEventDispatcher.CHOOSE_TOOLS_RIGHT,_owner,$fun,$args);
			JNEventDispatcher.getInstance().event(JNEventDispatcher.INeedTools,[$value,$tip]);
		}
		/**
		 *清除此界面的所有事件  包含子对象的事件和全局事件
		 * 切换一级页面和切换二级页面时自动调用
		 * 
		 */		
		public function removeAllListener():void{
			Laya.timer.clearAll(_owner);
			Laya.timer.clearAll(this);
			Data.rightToolValue="";
			JNEventDispatcher.getInstance().event(JNEventDispatcher.ClOSE_TOOLS);
			JNEventDispatcher.getInstance().offAll(JNEventDispatcher.CHOOSE_TOOLS_RIGHT);
			offSk();
			Laya.stage.offAll(Event.MOUSE_DOWN);
			Laya.stage.offAll(Event.MOUSE_MOVE);
			Laya.stage.offAll(Event.MOUSE_UP);
			Laya.stage.offAll(Event.CLICK);
			Laya.loader.clearUnLoaded();
			Dialog.closeAll();
			SoundManager.stopAllSound();
			Laya.timer.clearAll(ScriptSceneTools);
			//			Laya.timer.clear(JNEventDispatcher.getInstance(),JNEventDispatcher.getInstance().event);
		}
		private var downFun:Handler;
		private var upFun:Handler;
		private var endFun:Handler;
		private var moveFun:Handler;
		private var lastP:Point=new Point();
		private var isDown:Boolean=false;
		private var playstate:int=0;
		private var mouseTarget:Sprite;
		private var lockLastPoint:Boolean=false;
		private var distance:Number=0;
		private var playStart:int=0;
		/**
		 * 
		 * @param skName  要操作的龙骨动画
		 * @param nameOrIndex 动画名字或者索引
		 * @param direction 正确的操作方向
		 * @param playStart 播放开始的位置 （毫秒）
		 * @param playEnd 播放结束的位置（毫秒）
		 * @param hide 是否隐藏提示和指示
		 * @param endFun  动画执行完毕执行方法
		 *@param $per 每次拖动移动的量  值越小播放的速度越慢
		 * @param downFun 鼠标按下执行
		 * @param upFun  鼠标抬起执行
		 * @param isBack 是否可以逆向动画操作  有些动画不能逆向操作，比如手术刀划开皮肤
		 * @param $lastPoint 动画播放的开始位置，有些动画是在规定的位置区间滑动鼠标才播放的，比如像切口时，会用到。
		 */	
		public  function controlSkeleton(skName:Skeleton,nameOrIndex:*,$direction:String,$playStart:int,playEnd:int,$endFun:Handler,$per:int=40,$downFun:Handler=null,$upFun:Handler=null,$moveFun:Handler=null,$isBack:Boolean=true,$mouseTarget:Sprite=null,$startPoint:Point=null,$endPoint:Point=null):void
		{
			// TODO Auto Generated method stub
			playstate=$playStart;
			playStart=$playStart;
			downFun=$downFun;
			endFun=$endFun;
			moveFun=$moveFun;
			upFun=$upFun;
			if($mouseTarget!=null) {
				mouseTarget=$mouseTarget;
			}
			else{
				mouseTarget=Laya.stage;
			}
			Laya.stage.on(Event.MOUSE_UP,this,mouseUp);
			mouseTarget.on(Event.MOUSE_DOWN,this,mouseDown);
			mouseTarget.on(Event.MOUSE_MOVE,this,mouseMove,[skName,nameOrIndex,$direction,playStart,playEnd,$per,$isBack]);
			if($startPoint!=null){
				lockLastPoint=true;
				lastP=$startPoint;
				distance=Math.sqrt(Math.pow($endPoint.x-$startPoint.x,2)+Math.pow($endPoint.y-$startPoint.y,2));
			}
		}
		
		private function mouseUp(e:Event):void
		{
			// TODO Auto Generated method stub
			trace("up");
			if(!isDown) return ;
			isDown=false;
			upFun && upFun.runWith(this);
		}
		private function mouseDown():void{
			downFun && downFun.runWith(this);
			isDown=true;
			if(!lockLastPoint) lastP.setTo(Laya.stage.mouseX,Laya.stage.mouseY);
		}
		private function mouseMove(skName:Skeleton,nameOrIndex:*,direction:String,playStart:int,playEnd:int,per:int,isBack):void{
			var tempDuration:int=playEnd-playStart;
			if(isDown){
				moveFun && moveFun.runWith(this);
				switch(direction)
				{
					case "down":
					{
						if(Laya.stage.mouseY-lastP.y>0){//向下拖动鼠标
							if(lockLastPoint){
								playstate=(Laya.stage.mouseY-lastP.y)/distance*tempDuration;
							}
							else{
								playstate+=per;
							}
						}
						else{
							if(isBack && !lockLastPoint){
								playstate-=per;
							}
						}
						break;
					}
					case "up":
					{
						if(Laya.stage.mouseY-lastP.y<0){//向上拖动鼠标
							if(lockLastPoint){
								playstate=(lastP.y-Laya.stage.mouseY)/distance*tempDuration;
							}
							else{
								playstate+=per;
							}
						}
						else{
							if(isBack && !lockLastPoint){
								playstate-=per;
							}
						}
						break ;
					}
					case "left":
					{
						if(Laya.stage.mouseX-lastP.x<0){//向左拖动鼠标
							if(lockLastPoint){
								playstate=(lastP.x-Laya.stage.mouseX)/distance*tempDuration;
							}
							else{
								playstate+=per;
							}
						}
						else{
							if(isBack && !lockLastPoint){
								playstate-=per;
							}
						}
						break ;
					}
					case "right":
					{
						if(Laya.stage.mouseX-lastP.x>0){//向右拖动鼠标
							if(lockLastPoint){
								playstate=(Laya.stage.mouseX-lastP.x)/distance*tempDuration;
							}
							else{
								playstate+=per;
							}
						}
						else{
							if(isBack && !lockLastPoint){
								playstate-=per;
							}
						}
						break ;
					}
					default:
					{
						break;
					}
				}
				if((!lockLastPoint && playstate>=playEnd) || (lockLastPoint && playstate+playStart>=playEnd)){
					mouseTarget.off(Event.MOUSE_MOVE,this,mouseMove);
					mouseTarget.off(Event.MOUSE_DOWN,this,mouseDown);
					Laya.stage.off(Event.MOUSE_UP,this,mouseUp);
					isDown=false;
					if(lockLastPoint){
						skName.play(nameOrIndex,false,true,playstate+playStart-per);
					}
					else skName.play(nameOrIndex,false,true,playstate-per);
					skName.paused();
					endFun && endFun.runWith(this);
					return ;
				}
				if(playstate<playStart){
					playstate=playStart;
				}
				if(lockLastPoint) {
					if(playstate+playStart<skName.player.currentPlayTime) return ;
					skName.play(nameOrIndex,false,true,playStart+playstate);
				}
				else{
					skName.play(nameOrIndex,false,true,playstate);
					lastP.setTo(Laya.stage.mouseX,Laya.stage.mouseY);
				}
				skName.paused();
			}
		};
		private function offSk():void{
			if(mouseTarget){
				mouseTarget.off(Event.MOUSE_MOVE,this,mouseMove);
				mouseTarget.off(Event.MOUSE_DOWN,this,mouseDown);
			}
			Laya.stage.off(Event.MOUSE_UP,this,mouseUp);
		}
		
		/**
		 *实验最后一步结束，没有提交数据，在此特意写一个方法。 
		 *实验的最后一步时，需手动调用此方法。
		 * 
		 */		
		public function endShiyan():void
		{
			sendAddStepRequest(Data.currSonStep+1,false);
			if(Data.operationType==0){//如果是考核，不弹出实验结束的提示框
				Data.isSyStepComplete=true;
				//如果考核内容不包括实验报告，则自动考核完成的数据
				if(!Data.isNeedBaogao){
					Api.SaveExperiment(Data.operationType,Data.PracticeId,Data.UsedTime);
					ShiYanBaoGao.getInstance().examComplete();
				}
				//如果考核内容包括实验报告，则自动弹出实验报告
				else{
					ShiYanBaoGao.getInstance().popup();
				}
				return;
			}
			Api.SaveExperiment(Data.operationType,Data.PracticeId,Data.UsedTime,this,function(res){
				var that=this;
				if(Data.operationType==1 || (res.rows && res.rows.isfinish==0)){
					var eui:EndUI=new EndUI();
					if(eui.btn_exit){
						eshow();
					}
					else{
						eui.once("onViewCreated",this,eshow);
					}
					function eshow():void{
						eui.popup();
						eui.btn_baogao.once(Event.CLICK,this,function():void{
							eui.close();
							ShiYanBaoGao.getInstance().popup();
						});
						if(Data.operationType==2){
							eui.btn_replay.label='再做一次';
						}
						eui.btn_replay.once(Event.CLICK,this,function():void{
							eui.close();
							if(Data.token){
								Api.Restart(Data.PracticeId,Data.practiceInfo.experimentid,that,getData);
							}
							else{
								addPage(0);
							}
						});
						eui.btn_cancle.once(Event.CLICK,this,function():void{
							eui.close();
						});
						eui.btn_exit.once(Event.CLICK,this,function():void{
							eui.close();
							exitShiyan();
						});
					}
				}
				else{
					Browser.window.alert("任务完成");
					exitShiyan();
				}
				
			});
			
		}
		private function getData(data:Object):void
		{
			// TODO Auto Generated method stub
			if(data.success){
				Data.PracticeId=data.rows.practiceid;
				var url:String=Browser.window.location.href;
				url=url.split("?")[0];
				if(Data.operationType==1){
					Browser.window.location.href=url+"?token="+Data.token+"&practiceid="+Data.PracticeId;
				}else if(Data.operationType==2){
					Browser.window.location.href=url+"?token="+Data.token+"&pubtaskid="+Data.PracticeId;
				}
			}
			else{
				addPage(0);
			}
		}
		/**
		 *退出实验 
		 * 
		 */		
		public static function exitShiyan():void{
			
			/*if (Data.urlType=="1") 
			{
				Browser.window.location.href=Data.HttpURL+"/Student/Experiment/practice";
			}
			else if (Data.urlType=="2") 
			{
				Browser.window.location.href=Data.HttpURL+"/Teacher/Experiment/practice";
			}
			else if(Data.urlType=="3"){
				Browser.window.location.href=Data.WapURL+"/Student/Experiment/practice";
			}
			else if(Data.urlType=="4"){
				Browser.window.location.href=Data.WapURL+"/Teacher/Experiment/practice";
			}
			else{
				Browser.window.location.href=Data.HttpURL+"/Student/Experiment/practice";
			}*/
			if(Data.operationType==0){
				Browser.window.location.href=Data.httpurl_expTest;
			}
			else if(Data.operationType==2){
				Browser.window.location.href=Data.httpurl_task;
			}
			else Browser.window.location.href=Data.httpurl_syfl;
		}
		/**
		 *一个二级步骤操作完成，提交一次步骤用时 
		 * 
		 */		
		private function submitTime():void
		{
			trace("提交步骤:"+(Data.currStep+1)+"*"+Data.currSonStep+":用时="+Data.perStepTime+"秒");
			if(Data.token){
				if(Data.currSonStep>0){
					sendAddStepRequest(Data.currSonStep,true);
				}
				else changeSonSteps();
			}
			else changeSonSteps();
		}
		/**
		 *提示信息 
		 * @param str
		 * @param bAutoHide
		 * @param interval
		 * 
		 */		
		public function showTips(str:String,bAutoHide:Boolean=false,interval:int=5000):void{
			JNEventDispatcher.getInstance().event(JNEventDispatcher.SHOW_TIPS,[str,bAutoHide,interval]);
		}
		public function hideTips():void{
			JNEventDispatcher.getInstance().event(JNEventDispatcher.HIDE_TIPS);
		}
		/**
		 *更改二级步骤 
		 * @param $ind
		 * 
		 */		
		public function showSonStepByIndex($ind:int):void{
			JNEventDispatcher.getInstance().event(JNEventDispatcher.SHOW_SON_STEP,[$ind]);
		}
		/**
		 *跳转页面 
		 * @param $pageInt
		 * 
		 */		
		public function addPage($pageInt:int):void{
			JNEventDispatcher.getInstance().event(JNEventDispatcher.SHOW_STEP,[$pageInt]);
		}
	}
}